package cn.tedu.boot33.controller;

import cn.tedu.boot33.mapper.EmpMapper;
import cn.tedu.boot33.vo.Emp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class EmpController {
    //将Mapper自动装配到当前类里面,自动装配到Spring框架所提供的功能
    //自动装配注解到Spring框架和Mybatis框架的作用下自动创建了一个EmpMapper接口的实现类
    //并且实例化了该实现类
    @Autowired(required = false)    //required 必须的 required=false设置为非必须
    EmpMapper mapper;

    @RequestMapping("/select")
    @ResponseBody
    public String select(){
        List<Emp> list = mapper.select();
        //把员工的信息装进html标签中 最后返回给客户端
        String html = "<table border=1>";
        html+="<caption>员工列表</caption>";
        html+="<tr><th>id</th><th>名字</th><th>工作</th>" +
                "<th>年龄</th><th>工资</th><th>操作</th></tr>";
        for (Emp e:list) {
            html+="<tr>";
            html+="<td>"+e.getId()+"</td>";html+="<td>"+e.getName()+"</td>";
            html+="<td>"+e.getJob()+"</td>";html+="<td>"+e.getAge()+"</td>";
            html+="<td>"+e.getSalary()+"</td>";
            html+="<td><a href='/delete?id="+e.getId()+"'>删除</a></td>";
            html+="</tr>";
        }
        html+="</table><a href='/'>回到首页</a>";
        return html;
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String delete(int id){

        mapper.delete(id);
        return "删除完成!<a href='/select'>返回列表页面<a>";
    }

    @RequestMapping("/insert")
    @ResponseBody
    public String insert(Emp emp){
        mapper.insert(emp);
        return "添加完成!<a href='/select'>返回列表页面<a>";
    }

    @RequestMapping("/update")
    @ResponseBody
    public String update(Emp emp){
        System.out.println("emp = "+emp);
        mapper.update(emp);
        return "修改完成!<a href='/select'>返回列表页面</a>";
    }
}
